import menuApi from '@/api/menuApi'
import roleApi from '@/api/roleApi'
import type { IAction, IModalProps } from '@/types/modal'
import type { MenuItem } from '@/types/munuType'
import type { CreatePermission, RoleItem } from '@/types/roleType'
import { message } from '@/utils/AntdGlobal'
import { Form, Input, Modal, Tree } from 'antd'
import { useEffect, useImperativeHandle, useState } from 'react'

const SetPermission = (props: IModalProps<RoleItem>) => {
  const [form] = Form.useForm()
  const [visible, setVisible] = useState(false)
  const [data, setData] = useState<MenuItem[]>([])
  const [selectedKeys, setSelectedkeys] = useState<string[]>([])
  const [roleInfo, setRoleInfo] = useState<RoleItem>()
  const [permission, SetPermission] = useState<CreatePermission>()
  const getMenuList = async () => {
    const res = await menuApi.getMenuList()
    setData(res)
  }
  useImperativeHandle(props.mRef, () => {
    return {
      open
    }
  })
  const open = (type: IAction, data?: RoleItem) => {
    setVisible(true)
    if (data) {
      setRoleInfo(data)
      setSelectedkeys(data.permissionList?.checkedKeys || [])
    }
  }
  const handleTree = (checkedKeys: any, target: any) => {
    setSelectedkeys(checkedKeys)
    const seleted: string[] = []
    const parent: string[] = []
    target.checkedNodes.forEach((item: MenuItem) => {
      if (item.menuType === 2) {
        seleted.push(item._id)
      } else {
        parent.push(item._id)
      }
    })
    SetPermission({
      _id: roleInfo!._id,
      permissionList: {
        checkedKeys: seleted,
        halfCheckedKeys: parent
      }
    })
  }
  const handleSubmit = async () => {
    console.log(permission)
    await roleApi.updatePermission(permission as CreatePermission)
    message.success('权限设置成功')
    props.update()
    handleCancel()
  }
  const handleCancel = () => {
    setVisible(false)
  }
  useEffect(() => {
    getMenuList()
  }, [])
  return (
    <Modal
      title='设置权限'
      onOk={handleSubmit}
      onCancel={handleCancel}
      open={visible}
      width={800}
      okText='确定'
      cancelText='取消'
    >
      <Form form={form}>
        <Form.Item label='角色名称'>{roleInfo?.roleName}</Form.Item>
        <Form.Item label='权限列表'>
          <Tree
            checkedKeys={selectedKeys}
            fieldNames={{ title: 'menuName', key: '_id', children: 'children' }}
            onCheck={handleTree}
            checkable
            treeData={data}
          />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default SetPermission
